import https from 'https';
import fetch from 'fermionjs/lib/fetch';
import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('检查域名所属权失败');

export default function domainOwnershipCheck({ challenge, url }) {
	return fetch(url, {
		method: 'GET',
		headers: {
			'user-agent':
				'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36',
		},
		agent: function (_parsedURL) {
			// 忽略ssl证书检测
			if (_parsedURL.protocol === 'http:') return null;
			return new https.Agent({
				rejectUnauthorized: false,
			});
		},
		timeout: 5000,
		responseType: 'text',
	})
		.then(x => new RegExp(challenge, 'i').test(x))
		.catch(err => {
			// 错误代码404为未检测到校验文件
			const error = errorCodes['[0E]检查域名所属权失败'].from(err);
			this.log.error({ error, challenge, url }, error.rawMessage);
			return false;
		});
}
